package com.yutel.phone.binh.data;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.util.Log;

import com.yutel.phone.binh.data.database.DBQueryHelper;
import com.yutel.phone.binh.data.net.HttpHelper;
import com.yutel.phone.binh.data.net.NetHelper;
import com.yutel.phone.binh.data.vo.Channel;
import com.yutel.phone.binh.data.vo.Dict;
import com.yutel.phone.binh.data.vo.EpisodeSource;
import com.yutel.phone.binh.data.vo.EpisodeVideo;
import com.yutel.phone.binh.data.vo.Keyword;
import com.yutel.phone.binh.data.vo.Pinyin;
import com.yutel.phone.binh.data.vo.SearchDict;
import com.yutel.phone.binh.data.vo.SearchKeyword;
import com.yutel.phone.binh.data.vo.SearchPinyin;
import com.yutel.phone.binh.data.vo.Video;
import com.yutel.phone.binh.data.vo.VideoDetail;
import com.yutel.phone.binh.data.vo.VideoStream;
import com.yutel.phone.binh.data.xmlhandler.SAXforEpisodeHandler;

public class DataQuery {
	private final String TAG = "DataQuery";
	private Context context;

	public DataQuery(Context context) {
		this.context = context;
	}

	/**
	 * 初始化频道分类数据
	 */
	public void initData() {
		try {
			new BinhConfig(context);
			HttpHelper hh = new HttpHelper();
			DBQueryHelper db = new DBQueryHelper(context);
			String oldVer = BinhConfig.update;
			String newVer = hh.queryUpdateInfo();
			// init
			Log.i(TAG, "oldVer=" + oldVer + ",newVer=" + newVer);
			if (oldVer != null && oldVer != null && !oldVer.equals(newVer)) {
				boolean channel = false, dict = false;
				// Init Channel
				ArrayList<Channel> list = hh.queryChannel(newVer);
				if (db.initChannelCategory(list)) {
					channel = true;
				}
				// SearchDic
				SearchDict req = new SearchDict();
				req.setAcount("aaa");
				req.setVersion(newVer);
				NetHelper nh = NetHelper.getInstance();
				SearchDict dicts = nh.searchDicALL(req);
				if (dicts != null) {
					if (db.initDict(dicts.getList())) {
						dict = true;
					}
				}
				// save database
				if (channel && dict) {
					BinhConfig.setUpdate(newVer);
					Log.i(TAG, "newVer is saved");
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
		}
	}

	/**
	 * 获取精彩推荐节目
	 * 
	 * @return
	 */
	public ArrayList<Video> pullRecommend() {
		try {
			HttpHelper hh = new HttpHelper();
			return hh.queryRecommend();
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
			return null;
		}
	}

	/**
	 * 获取频道与分类
	 * 
	 * @return
	 */
	public ArrayList<Channel> getChannel() {
		try {
			DBQueryHelper db = new DBQueryHelper(context);
			ArrayList<Channel> list = db.getChannel();
			for (Channel channel : list) {
				channel.setCategoryList(db.getCategory(channel.getId()));
			}
			return list;
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
			return null;
		}
	}

	/**
	 * 通过分类获取节目
	 * 
	 * @param categoryid
	 * @return
	 */
	public ArrayList<Video> pullVediosByCategoryid(String categoryid) {
		try {
			HttpHelper hh = new HttpHelper();
			return hh.pullVediosByCategoryid(categoryid);
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
			return null;
		}
	}

	/**
	 * 查询视频详细信息
	 * 
	 * @param mid
	 * @return
	 */
	public VideoDetail queryVideoInfo(String mid) {
		try {
			HttpHelper hh = new HttpHelper();
			return hh.queryVideoInfo(mid);
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
			return null;
		}
	}

	/**
	 * 查询播放源
	 * 
	 * @param req
	 * @return
	 */
	public ArrayList<EpisodeSource> queryEpisode(String videoId) {
		ArrayList<EpisodeSource> list = null;
		try {
			DBQueryHelper db = new DBQueryHelper(context);
			if (videoId != null) {
				String vid = videoId.replaceAll("v", "").trim();
				if (!"vid".equals(vid)) {
					long lvid = Long.valueOf(vid);
					SearchKeyword req = new SearchKeyword();
					req.setAcount("aaa");
					req.setVid(lvid);
					NetHelper nh = NetHelper.getInstance();
					SearchKeyword sk = nh.KeywordSearch(req);
					if (sk != null) {
						list = new ArrayList<EpisodeSource>();
						SAXParserFactory spf = SAXParserFactory.newInstance();
						SAXforEpisodeHandler episodeHandler = new SAXforEpisodeHandler();
						SAXParser saxparser = spf.newSAXParser();
						Dict vo = new Dict();
						vo.setType(1);
						for (Keyword key : sk.getList()) {
							ByteArrayInputStream bais = new ByteArrayInputStream(
									key.getValue().getBytes());
							saxparser.parse(bais, episodeHandler);
							EpisodeSource source = episodeHandler.getSource();
							EpisodeSource estemp = null;
							for (EpisodeSource es : list) {// 查找已存在的源
								if (es.getType().equals(source.getType())) {
									estemp = es;
									break;
								}
							}
							if (estemp != null) {// 放入相同的源中
								if (source.getList() != null
										&& source.getList().size() > 0) {
									for (EpisodeVideo ev : source.getList()) {
										estemp.getList().add(ev);
									}
								}
							} else {// 新生成一个源
								vo.setNum(key.getSourceType());
								Dict temp = db.getDict(vo);
								if (temp != null) {
									source.setTypeName(temp.getValue());
								}
								list.add(source);
							}
						}
					}
				}
			}
			return list;
		} catch (Exception e) {
			Log.e(TAG, "iqueryEpisode()", e);
			return null;
		}
	}

	/**
	 * 影片搜索
	 * 
	 * @param name
	 * @param index
	 * @param count
	 * @return
	 */
	public SearchPinyin search(String name, int index, int count) {
		try {
			NetHelper hh = NetHelper.getInstance();
			SearchPinyin req = new SearchPinyin();
			req.setAcount("aaa");
			req.setPinyin(name);
			req.setIndex(index);
			req.setCount(count);
			SearchPinyin result = hh.PinyinSearch(req);
			if (result != null) {
				DBQueryHelper db = new DBQueryHelper(context);
				Dict d = new Dict();
				d.setType(2);
				for (Pinyin py : result.getList()) {
					d.setNum(py.getChannelType());
					Dict dict = db.getDict(d);
					if (dict != null) {
						py.setDict(dict);
					}
				}
			}
			return result;
		} catch (Exception e) {
			Log.e(TAG, "initData error!", e);
			return null;
		}
	}

	public VideoStream videoStream(String url,String type) {
		try {
			VideoQuery vq=new VideoQuery();
			if("qiyi".equals(type)) {
				return vq.qiyi(url);
			}
			return null;
		} catch (Exception e) {
			Log.e(TAG, "videoStream()", e);
			return null;
		}
	}
}
